<script>
import { isAvailable } from '@/utils/kris_utils'

export default {
  props: {
    members: {
      type: Array,
      required: true,
      default() {
        return []
      }
    },
    employees: {
      type: Array,
      required: true,
      default() {
        return []
      }
    },
    loading: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    fetchEmployeesFn: {
      type: Function,
      default: (kw) => console.log(kw)
    }
  },
  data() {
    return {
      fetchEmployeeLoading: false,
      memberIDs: [],
      pagination: {
        pageSize: 10,
        currentPage: 1
      },
      addRoleUser: [],
      genderOptions: {
        1: '男',
        0: '女'
      },
      employeeMap: []
    }
  },
  computed: {
    // 把已经存在宇列表的去除
    employeesWithFilter() {
      return this.employees
        .filter(employee => {
          return !isAvailable(this.membersMap.get(employee.id))
        })
        .map(item => {
          return {
            label: item.name,
            value: item.id
          }
        })
    },
    membersMap() {
      const m = new Map()
      for (const member of this.members) {
        m.set(member.id, member)
      }
      return m
    },
    // employeeMap() {
    //   const m = new Map()
    //   for (const employee of this.employees) {
    //     m.set(employee.id, employee)
    //   }
    //   return m
    // },
    membersWithPagination() {
      const { currentPage, pageSize } = this.pagination
      const beginPos = currentPage * pageSize - pageSize
      const endPos = beginPos + pageSize
      const len = this.members.length
      const finalEndPos = endPos > len ? len : endPos

      return this.members.slice(beginPos, finalEndPos)
    },
    totalPage() {
      return this.members.length
    }
  },
  created() {
    this.setEmployeeMap()
  },
  methods: {
    async fetchUsers(kw) {
      try {
        this.fetchEmployeeLoading = true
        await this.fetchEmployeesFn(kw)
        this.fetchEmployeeLoading = false
      } catch (e) {
        this.fetchEmployeeLoading = false
        throw e
      }
    },
    handleCurrentPageChange(n) {
      this.pagination.currentPage = n
    },
    toProfile(row) {
      this.$router.push({
        path: `/personnel-files/show/${row.id}`,
        query: { tag_title: row.name + '-档案', show: true }
      })
    },
    saveSelected() {
      const data = this.memberIDs
        .map(id => this.employeeMap.get(id))
        .filter(item => isAvailable(item))

      console.log('data --------->', data)

      for (let i = 0; i < this.memberIDs.length; i++) {
        const item = this.memberIDs[i]
        if (!this.addRoleUser.includes(item)) {
          this.addRoleUser.push(data[i])
        }
      }

      this.$emit('onRoleUser', this.addRoleUser)
      this.members.unshift(...data)
      this.memberIDs = []
    },
    async removeItem(row) {
      console.log(row, 'row')
      this.$confirm(
        '是否将其从该角色中移除？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        const index = this.members.findIndex(item => row.id == item.id)
        const roleIndex = this.addRoleUser.findIndex(item => item.id === row.id)
        if (index !== -1) {
          this.$emit('onDelRole', row.id)
          this.members.splice(index, 1)
        }

        if (roleIndex !== -1) {
          this.addRoleUser.splice(roleIndex, 1)
          this.$emit('onRoleUser', this.addRoleUser)
        }
      })
    },

    setEmployeeMap() {
      const m = new Map()
      for (const employee of this.employees) {
        m.set(employee.id, employee)
      }
      this.employeeMap = m
    }
  }
}
</script>

<template>
  <div class="role-member-editor-container">
    <div class="header">
      <div style="flex: 1;padding-right: 4px;">
        <el-select
          v-model="memberIDs"
          filterable
          remote
          clearable
          multiple
          placeholder="请选择用户（可输入用户姓名搜索）"
          style="width: 100%;"
          :disabled="disabled"
          :remote-method="fetchUsers"
          :loading="fetchEmployeeLoading"
        >
          <el-option
            v-for="item in employeesWithFilter"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <el-button type="primary" :disabled="disabled" @click="saveSelected">添加</el-button>
    </div>
    <div class="body">
      <el-table
        v-loading="loading"
        :data="membersWithPagination"
        border
        style="width: 100%"
      >
        <el-table-column
          prop="name"
          label="姓名"
        />
        <el-table-column
          prop="gender"
          label="性别"
        >
          <template v-slot="{ row }">
            {{ genderOptions[row.gender] ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="phone"
          label="电话"
        />

        <el-table-column
          label="操作"
        >
          <template slot-scope="scope">

            <el-button
              :disabled="disabled"
              size="small"
              type="text"
              @click="removeItem(scope.row)"
            >
              移除
            </el-button>

            <el-button
              :disabled="disabled"
              size="small"
              type="text"
              @click="toProfile(scope.row)"
            >
              档案
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="prev, pager, next"
        :total="totalPage"
        :disabled="disabled"
        @current-change="handleCurrentPageChange"
      />
    </div>
  </div>
</template>

<style lang="scss">
.role-member-editor-container {
    .header {
        display: flex;
    }
    .body {
        padding: 10px 0;

        .el-pagination {
            text-align: right;
            padding: 10px 0;
        }
    }
}
</style>
